Conditional (computer programming)
part 15/26 · 46.2 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
In contrast to other languages, in Smalltalk the conditional statement is not a language construct but defined in the class Boolean as an abstract method that takes two parameters, both closures. Boolean has two subclasses, True and False, which both define the method, True executing the first closure only, False executing the second closure only.cite-ref-smalltalk-conditionals-12-0[12]
var = condition
ifTrue: [ 'foo' ]
ifFalse: [ 'bar' ]
JavaScript
JavaScript uses if-else statements similar to those in C languages. A Boolean value is accepted within parentheses between the reserved if keyword and a left curly bracket.
if (Math.random() < 0.5) {
console.log("You got Heads!");
} else {
console.log("You got Tails!");
}
The above example takes the conditional of Math.random() < 0.5 which outputs true if a random float value between 0 and 1 is greater than 0.5. The statement uses it to randomly choose between outputting You got Heads! or You got Tails! to the console. Else and else-if statements can also be chained after the curly bracket of the statement preceding it as many times as necessary, as shown below:
var x = Math.random();
if (x < 1/3) {
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────